package com.hue.controller;

import com.hue.entity.EmailUtils;
import com.hue.entity.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private EmailUtils emailUtils;

    @Autowired
    private RedisTemplate<String,String > redisTemplate;

    /*
       发送邮件到那个地址
    */
    @GetMapping("/sendEmail/{to}")
    public R sendEmail(@PathVariable("to") String to) {
        try {
            Random random = new Random();
            //生成6位数随机验证码
            String checkCode = "";
            for (int i = 0; i < 6; i++) {
                checkCode += random.nextInt(10);
            }
            //发送的内容
            String text = "您的注册验证码为：" + checkCode + "，5分钟内有效！";
            new Thread(()->{
                //发送邮件
                emailUtils.sendEmail(to, "验证码邮件",text);
            }).start();
            //将验证码存储到redis中,用to作为key，验证码为value，过期时间为5分钟
            redisTemplate.opsForValue().set(to,checkCode,5, TimeUnit.MINUTES);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return R.error();
        }
        return R.ok();
    }
}
